<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Office文件离线预览器</title>
    <!-- 引入样式文件 -->
    <link rel="stylesheet" href="./css/viewer.css">
    <link rel="stylesheet" href="./css/pptxjs.css">
    <link rel="stylesheet" href="./css/nv.d3.min.css">
</head>
<body>
    <div id="preview-container">
        <div id="sheet-tabs"></div>
        <div id="excel-preview"></div>
        <div class="loading">正在加载文件预览器...</div>
    </div>

    <script>
        // 文件预览配置
        const previewConfig = {
            pptx: function(url, container) {
                try {
                    $(container).pptxToHtml({
                        pptxFileUrl: url,
                        slideMode: false,
                        keyBoardShortCut: false,
                        slideModeConfig: {
                            first: 1,
                            nav: false,
                            navTxtColor: "white",
                            navNextTxt:"&#8250;",
                            navPrevTxt: "&#8249;",
                            showPlayPauseBtn: false,
                            keyBoardShortCut: false,
                            showSlideNum: false,
                            showTotalSlideNum: false,
                            autoSlide: false,
                            randomAutoSlide: false,
                            loop: false,
                            background: "black",
                            transition: "default",
                            transitionTime: 1
                        }
                    });
                } catch (error) {
                    container.innerHTML = '<div class="error">PPTX预览失败: ${error.message}</div>';
                }
            },
            xlsx: function(url, container) {
                const excelPreview = document.getElementById('excel-preview');
                const sheetTabs = document.getElementById('sheet-tabs');
                
                excelPreview.innerHTML = '<p class="loading">正在加载Excel...</p>';
                
                fetch(url)
                    .then(response => {
                        if (!response.ok) throw new Error('文件加载失败');
                        return response.arrayBuffer();
                    })
                    .then(data => {
                        const workbook = XLSX.read(data, { type: 'array' });
                        renderSheetTabs(workbook, sheetTabs, excelPreview);
                        showSheet(workbook, workbook.SheetNames[0], excelPreview);
                    })
                    .catch(error => {
                        excelPreview.innerHTML = '<div class="error">加载失败: ${error.message}</div>';
                    });
            },
            docx: function(url, container) {
                fetch(url)
                    .then(response => response.arrayBuffer())
                    .then(arrayBuffer => {
                        mammoth.convertToHtml({arrayBuffer: arrayBuffer})
                            .then(result => {
                                container.innerHTML = result.value;
                            })
                            .catch(e => {
                                container.innerHTML = '<div class="error">DOCX预览失败: ${e.message}</div>';
                            });
                    })
                    .catch(e => {
                        container.innerHTML = '<div class="error">文件加载失败: ${e.message}</div>';
                    });
            },
            doc: function(url, container) {
                container.innerHTML = `
                    <div class="error">
                        该预览器不支持 .doc 文件的预览。建议将文件转换为 .docx 格式后重试。<br>
                        您可以使用 Microsoft Word 或在线转换工具进行转换。
                    </div>
                `;
            },
            ppt: function(url, container) {
                container.innerHTML = `
                    <div class="error">
                        该预览器不支持 .ppt 文件的预览。建议将文件转换为 .pptx 格式后重试。<br>
                        您可以使用 Microsoft PowerPoint 或在线转换工具进行转换。
                    </div>
                `;
            },
            xls: function(url, container) {
                const excelPreview = document.getElementById('excel-preview');
                const sheetTabs = document.getElementById('sheet-tabs');
                
                excelPreview.innerHTML = '<p class="loading">正在加载Excel...</p>';
                
                fetch(url)
                    .then(response => {
                        if (!response.ok) throw new Error('文件加载失败');
                        return response.arrayBuffer();
                    })
                    .then(data => {
                        const workbook = XLSX.read(data, { type: 'array' });
                        renderSheetTabs(workbook, sheetTabs, excelPreview);
                        showSheet(workbook, workbook.SheetNames[0], excelPreview);
                    })
                    .catch(error => {
                        excelPreview.innerHTML = '<div class="error">加载失败: ${error.message}</div>';
                    });
            },
            default: function(url, container) {
                container.innerHTML = `
                    <div class="error">
                        暂不支持该文件类型的预览。支持的文件类型包括: .docx, .pptx, .xlsx<br>
                        如需预览 .doc 或 .ppt 文件，请先将其转换为 .docx 或 .pptx 格式。
                    </div>
                `;
            }
        };

        // 渲染 Excel Sheet 标签
        function renderSheetTabs(workbook, sheetTabs, excelPreview) {
            sheetTabs.innerHTML = '';
            workbook.SheetNames.forEach(sheetName => {
                const tab = document.createElement('div');
                tab.className = 'sheet-tab';
                tab.textContent = sheetName;
                if (sheetName === workbook.SheetNames[0]) {
                    tab.classList.add('active');
                }
                tab.onclick = () => showSheet(workbook, sheetName, excelPreview);
                sheetTabs.appendChild(tab);
            });
        }

        // 显示指定的 Excel Sheet
        function showSheet(workbook, sheetName, excelPreview) {
            // 清空内容以确保旧内容被移除
            excelPreview.innerHTML = '';
            
            document.querySelectorAll('.sheet-tab').forEach(tab => {
                tab.classList.toggle('active', tab.textContent === sheetName);
            });
            
            const worksheet = workbook.Sheets[sheetName];
            
            if (!worksheet || Object.keys(worksheet).length === 0) {
                excelPreview.innerHTML = '<div class="empty-sheet">此工作表为空</div>';
                return;
            }
            
            // 由于 xlsx.full.min.js:13 的错误，添加安全检查
            try {
                const html = XLSX.utils.sheet_to_html(worksheet);
                excelPreview.innerHTML = html;
            } catch (error) {
                console.error("渲染工作表时出错:", error);
                excelPreview.innerHTML = '<div class="error">渲染工作表时出错: ${error.message}</div>';
            }
        }

        // 从二进制数据中提取可读文本
        function extractTextFromBinary(buffer) {
            const uint8Array = new Uint8Array(buffer);
            let text = '';
            for (let i = 0; i < uint8Array.length; i++) {
                if (uint8Array[i] >= 32 && uint8Array[i] <= 126) {
                    text += String.fromCharCode(uint8Array[i]);
                } else if (uint8Array[i] === 10 || uint8Array[i] === 13) {
                    text += '\n';
                }
            }
            return text.length > 0 ? text : '无法提取可读文本内容';
        }

        // 获取URL参数
        function getUrlParam(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }

        // 获取文件类型
        function getFileType(filename) {
            const ext = filename.split('.').pop().toLowerCase();
            return {
                'doc': 'doc',
                'docx': 'docx',
                'ppt': 'ppt',
                'pptx': 'pptx',
                'xls': 'xls',
                'xlsx': 'xlsx'
            }[ext] || null;
        }

        // 加载文件
        function loadFile(fileUrl, container) {
            const filename = fileUrl.split('/').pop().split('?')[0];
            const fileType = getFileType(filename);
            
            if (!fileType) {
                container.innerHTML = '<div class="error">不支持的文件类型: ${filename}</div>';
                return;
            }

            // 移除加载提示
            const loadingElement = container.querySelector('.loading');
            if (loadingElement) {
                loadingElement.remove();
            }

            // 清空预览容器
            container.innerHTML = '<div id="sheet-tabs"></div><div id="excel-preview"></div>';
            
            previewConfig[fileType || 'default'](fileUrl, container);
        }

        // 页面加载时检查URL参数
        window.onload = function() {
            const previewContainer = document.getElementById('preview-container');
            const fileUrl = getUrlParam('file');
            
            if (fileUrl) {
                loadFile(decodeURIComponent(fileUrl), previewContainer);
            } else {
                previewContainer.innerHTML = '<div class="error">请通过URL参数指定要预览的文件</div>';
            }
        };
    </script>
    <script type="text/javascript" src="./js/jquery-1.11.3.min.js"></script>
    <script type="text/javascript" src="./js/jszip.min.js"></script>
    <script type="text/javascript" src="./js/filereader.js"></script>
    <script type="text/javascript" src="./js/d3.min.js"></script>
    <script type="text/javascript" src="./js/nv.d3.min.js"></script>
    <script type="text/javascript" src="./js/divs2slides.js"></script>
    <script type="text/javascript" src="js/pptxjs.js"></script>
    <script type="text/javascript" src="js/mammoth.browser.min.js"></script>
    <script type="text/javascript" src="js/xlsx.full.min.js"></script>
</body>
</html>